/**
 * @Author: Nico
 */
//必须带done回调 执行完成调用
import { gp } from '@vui'
import merge from 'lodash/merge'
import isArray from 'lodash/isArray'
import trim from 'lodash/trim'
import { getModelByModelTree, replaseRegVariable, processingConstant } from '@ve/utils/utils'
import cloneDeep from 'lodash/cloneDeep'
import isEmpty from 'lodash/isEmpty'

import { translateTitle } from '@/utils/i18n'
export default function pdaInjectData({ vm, action, done, callbackData }) {
  const modelIdList = action.extension.receiveObject.value && action.extension.receiveObject.value.source
  const modelTree = vm.$store.state.preview.pages[vm.$store.state.preview.nowPageId]
  // console.log('注入自定义参数PDA数据参数', modelIdList, modelTree)
  modelIdList.forEach((modelId) => {
    let _model = getModelByModelTree(modelId, modelTree)
    let dataObj = {}
    if (_model) {
      if (action.extension.pdaInjectData.useLastData) {
        // 如果选择为使用上次任务数据
        let callbackDataObj = null
        if (isArray(callbackData)) {
          callbackDataObj = cloneDeep(callbackData[0])
          // 如果有配置获取多值 则进行值拼接
          if (action.extension.pdaInjectData.getMoreValueKey) {
            const getDataKeyList = action.extension.pdaInjectData.getMoreValueKey.split(',')
            getDataKeyList.map((item) => {
              item = trim(item)
              callbackDataObj[item] = ''
              callbackData.forEach((dataItem) => {
                if (!callbackDataObj[item]) {
                  callbackDataObj[item] = dataItem[item] || ''
                } else {
                  callbackDataObj[item] = callbackDataObj[item] + `${action.extension.pdaInjectData.getMoreValueJoinSym}` + `${dataItem[item] || ''}`
                }
              })
            })
          }
        } else {
          callbackDataObj = callbackData
        }
        // }
        // 根据获取数据路径筛选数据
        const getDataPath = action.extension.pdaInjectData.getDataPath || ''
        if (trim(getDataPath)) {
          if (getDataPath.indexOf('->') !== -1) {
            const fieldList = getDataPath.split('->')
            // window.cacheObj[b] = _callbackData
            fieldList.forEach((fieldItem) => {
              // 如果没有后续值则不继续往下取值
              if (callbackDataObj[trim(fieldItem)] === undefined) return
              callbackDataObj = callbackDataObj[trim(fieldItem)]
            })
          } else {
            callbackDataObj = callbackDataObj[trim(getDataPath)] || {}
          }
        }
        const getDataKey = action.extension.pdaInjectData.getDataKey
        const injectDataKey = action.extension.pdaInjectData.injectDataKey || ''
        if (!trim(getDataKey)) {
          // 如果没有获取数据Key 则返回全量数据
          dataObj = cloneDeep(callbackDataObj)
        } else {
          const getDataKeyList = getDataKey.split(',')
          if (!injectDataKey) {
            // 如果没有注入数据 key 则返回获取数据key
            getDataKeyList.map((item) => {
              item = trim(item)
              dataObj[item] = callbackDataObj[item]
            })
          } else {
            // 如果有注入数据 key
            const injectDataKeyList = injectDataKey.split(',')
            getDataKeyList.map((item, index) => {
              item = trim(item)
              // 有注入数据 key 则用注入数据 key, 没有则用获取数据 key
              const dataKey = injectDataKeyList[index] || item
              dataObj[dataKey] = callbackDataObj[item]
            })
          }
        }

        if (_model.type === 'uiPdaUpload') {
          const obj = cloneDeep(_model.extension.requestData) || {}
          obj.value.forEach((item) => {
            if (dataObj[item.key]) {
              item.value = dataObj[item.key]
            }
          })
          _model.extension.requestData = obj
        }
      } else {
        const dataList = action.extension.pdaInjectData.value
        dataList.forEach((item) => {
          // 做常量转化
          if (action.extension.pdaInjectData.constantTransformation) {
            dataObj[item.key] = processingConstant(vm, item.value)
          } else {
            dataObj[item.key] = item.value
          }
        })
      }

      if (_model.type === 1 || _model.type === 2) {
        // 如果组件为页面类型 则将数据注入到 requestData
        _model.data.requestData ? '' : (_model.data.requestData = {})
        merge(_model.data.requestData, dataObj)
      } else {
        if (!isEmpty(vm.vuiComponents)) {
          for (let v in vm.vuiComponents) {
            if (vm.vuiComponents[v].self.info.type == 'uiPdaSelect') {
              let extension = vm.vuiComponents[v].self.info.extension
              let chaceItem = extension.optionConfig.value.find((vv) => {
                return vv[extension.valueField.value] == dataObj[extension.model.value]
              })
              if (!isEmpty(chaceItem)) {
                vm.vuiComponents[v].self.formDataModelLabel = chaceItem[extension.labelField.value]
              }
            }
          }
        }

        // 否则将数据注入到 formData
        if (!_model.data || !_model.data.formData) {
          _model.data = {}
          _model.data.formData = {}
        }

        if (
          isArray(dataObj) &&
          _model.type !== 'uiPdaTable' &&
          _model.type !== 'uiPdaCard' &&
          _model.type !== 'uiPdaSelect' &&
          _model.type !== 'uiPdaPagination'
        ) {
          dataObj = dataObj[0]
        }
        merge(_model.data.formData, dataObj)
      }
      // 自定义注入参数---输入框
      const customParam = action.extension.pdaInjectData.customParam
      if (customParam && _model.type === 'uiPdaInput' && vm.vuiComponents[_model._id]) {
        // 判断是否有变量配置
        let inputVal = ''
        if (/#{.*?}/g.test(customParam)) {
          // 变量解析
          // console.log('注入自定义参数-变量解析', )
          inputVal = replaseRegVariable(customParam, callbackData)
        } else {
          // 给输入框设置死得值
          inputVal = customParam
        }
        vm.vuiComponents[_model._id].self.$setInput(inputVal)
      }

      //  Nico操作表格数据注入
      if (_model.type === 'uiPdaTable') {
        _model.data.formData = cloneDeep(dataObj)
        const tableSelf = vm.vuiComponents[_model._id]
        if (!isEmpty(tableSelf) && _model.data.formData.length == 0) {
          // 当给表格数据注入空数组是。全选取消
          tableSelf.self.checkboxAll = false

          tableSelf.self.allData = []
        }
      }

      // Nico数据注入方式渲染下拉选
      if (_model.type === 'uiPdaSelect') {
        _model.extension.optionConfig.value = cloneDeep(Object.values(dataObj))
      }

      // Afun 数据注入方式渲染分页器 // Nico数据注入方式渲染卡片
      if (_model.type === 'uiPdaPagination' || _model.type === 'uiPdaCard') {
        _model.data.formData = cloneDeep(Object.values(dataObj))
      }

      console.log('数据注入', _model.data.formData, dataObj)
      vm.$store.commit('preview/setPageData', modelTree)
      // 提交 dispatch 触发页面组件状态更新（ dataObj 为传递的数据对象，moduleObj 为目标组件对象
      // vm.$store.dispatch('pageModulesState/setPageModulesStateByObj', { dataObj: dataObj, moduleObj: _model })
      // vm.$store.dispatch('pageModulesState/setPageModulesStatesByObj', {
      //   pageId: vm.$store.getters['preview/getNowPageId'],
      //   pageState: { dataObj: dataObj, moduleObj: _model },
      // })
    } else {
      gp.$baseMessage(translateTitle('Pda.elements.数据注入提示'), 'warning')
    }
  })
  vm.$nextTick(() => {
    if (done) {
      done(null, callbackData)
    }
  })
}
